package com.hula.onion.book.server.spider.platforms.lidecaifu;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/17 19:33
 *
 * @author shan
 * @version 1.0
 */
@Component("liDeCaiFuSpider")
public class LiDeCaiFuSpider extends SpiderCommon {
    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://www.leadercf.com/auth/login";
    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://www.leadercf.com/center";


    @Autowired
    private LiDeCaiFuSpiderHelper niWoDaiSpiderHelper;

    /**
     * 执行爬取操作
     * 1.获取 RSA key
     * 2.组装模拟登陆参数，模拟登陆
     * 3.爬取用户详细信息
     */
    @Override
    public CommonResponse execute() {

        CommonResponse commonResponse = new CommonResponse(ResponseStatusEnum.FAIL);
        //1.1 组装模拟登陆参数
        HttpClientContext httpContext = HttpClientContext.create();
        BasicCookieStore cookieStore = new BasicCookieStore();
        httpContext.setCookieStore(cookieStore);
        try {
            Map<String, Object> params =
                    niWoDaiSpiderHelper.installRequestParams(loginForm, "");
            //1.2 登陆
            String responseStr = HttpUtils.post(LOGIN_URL, params, httpContext);
            logger.info("[liDeCaiFuSpider] Http response result:{}", responseStr);
            //2.2 解析HTML
            LiDeCaiFuResponseEntity liDeCaiFuResponseEntity = JSONObject.parseObject(responseStr, LiDeCaiFuResponseEntity.class);

            if ("000".equals(liDeCaiFuResponseEntity.getCode())) {
                //3.1 获取个人信息
                String result = HttpUtils.get(GET_ACCOUNT_INFO_URL, httpContext);
                //3.2 解析HTML
                String accountBalance = niWoDaiSpiderHelper.parseAccountBalance(result);
                commonResponse = new CommonResponse(ResponseStatusEnum.SUCCESS);
                commonResponse.setData(accountBalance);
            } else {
                commonResponse.setMsg(niWoDaiSpiderHelper.parsErrorMessage(responseStr));
                commonResponse.setCode("-1");
            }

        } catch (Exception e) {
            commonResponse = new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
            logger.error("[liDeCaiFuSpider] Install request params error!");
        }

        return commonResponse;
    }
}
